package com.k.base.jdk.stream.listbeantomap;

import com.k.base.jdk.stream.domain.Person;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ListBeanToMapTest {
    public static void main(String[] args) {
        List<Person> list = getData();
        System.out.println(list);

        //  id 重复报错
        Map<String,Person> map = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));
        System.out.println("map:"+map);

        // id 重复使用最后一个
        Map<String, Person> map1 = list.stream().collect(Collectors.toMap(Person::getId, a -> a, (k1, k2) -> k2));
        System.out.println("map1:" + map1);

        // id 重复使用最后一个
        Map<String, Person> map2 = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (key1, key2) -> key2));
        System.out.println("map2:" + map2);

        // Stream 分组
        Map<Integer,List<Person>> groupByAge = list.stream().collect(Collectors.groupingBy(Person::getAge));
        System.out.println("根据age分组："+groupByAge);
    }

    public static List<Person> getData() {
        List<Person> list = new ArrayList<>();
        Date now = new Date();
        for (int i = 0; i < 5; i++) {
            Person p = new Person("id" + i, "tom" + i, 20 + i, now);
            list.add(p);
        }
        Person p = new Person("id" + 3, "jim" + 3, 20 + 3, now);
        list.add(p);
        return list;
    }
}
